#ifndef LOG_MANAGER_HPP
#define LOG_MANAGER_HPP

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <mutex>
#include <algorithm>

class LogManager {
public:
    enum class LogLevel {
        INFO,
        WARNING,
        ERROR
    };
    // 获取 LogManager的单例实例
    static LogManager& getInstance(const std::string& filename) {
        static LogManager instance(filename);
        return instance;
    }

    // 防止拷贝和赋值操作
    LogManager(const LogManager&) = delete;
    LogManager& operator=(const LogManager&) = delete;


    // 记录日志信息
    void log(LogLevel level, const std::string& message) {
        // 使用互斥锁保护对日志文件的访问
        std::lock_guard<std::mutex> lock(mutex_);
        std::ofstream file(filename_, std::ios::app);
        if (!file.is_open()) {
            std::cerr << "Error: Unable to open log file." << std::endl;
            return;
        }

        std::string level_str;
        switch (level) {
            case LogLevel::INFO:
                level_str = "[INFO] ";
                break;
            case LogLevel::WARNING:
                level_str = "[WARNING] ";
                break;
            case LogLevel::ERROR:
                level_str = "[ERROR] ";
                break;
        }

        std::time_t now = std::time(nullptr);
        std::string time_str = std::ctime(&now);
        // 删除时间字符串中的换行符
        time_str.erase(std::remove(time_str.begin(), time_str.end(), '\n'), time_str.end());

        file << time_str << " " << level_str << message << std::endl;
        file.close();
    }

    // 检索和过滤日志信息
    void search(const std::string& keyword) {
        // 使用互斥锁保护对日志文件的访问
        std::lock_guard<std::mutex> lock(mutex_);
        std::ifstream file(filename_);
        if (!file.is_open()) {
            std::cerr << "Error: Unable to open log file." << std::endl;
            return;
        }

        std::string line;
        while (std::getline(file, line)) {
            if (line.find(keyword) != std::string::npos) {
                std::cout << line << std::endl;
            }
        }
        file.close();
    }
    // 日志存储：将日志信息存储到文件
    void store(const std::string& message) {
        // 使用互斥锁保护对日志文件的访问
        std::lock_guard<std::mutex> lock(mutex_);
        std::ofstream file(filename_, std::ios::app);
        if (!file.is_open()) {
            std::cerr << "Error: Unable to open log file." << std::endl;
            return;
        }

        std::time_t now = std::time(nullptr);
        std::string time_str = std::ctime(&now);
        // 删除时间字符串中的换行符
        time_str.erase(std::remove(time_str.begin(), time_str.end(), '\n'), time_str.end());
    
        file << time_str << " " << message << std::endl;
        file.close();
    }


private:
    LogManager(const std::string& filename) : filename_(filename) {}
    std::string filename_;
    std::mutex mutex_; // 添加互斥锁，用于保护对日志文件的访问
};

#endif // LOG_MANAGER_HPP